﻿using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;

namespace MvcWebRoleUpload.Models
{
    public class BlobStorageHelper : IStorageHelper
    {
        private CloudBlobContainer blobContainer;

        public BlobStorageHelper()
        {
            // Retrieve storage account from connection-string
            string connString = RoleEnvironment.GetConfigurationSettingValue("BlobStorageUpload");
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connString);

            // Create the blob client 
            CloudBlobClient blobClient;
            blobClient = storageAccount.CreateCloudBlobClient();

            // Retrieve a reference to a container 
            blobContainer = blobClient.GetContainerReference("files");

            // Create the container if it doesn't already exist
            if (blobContainer.CreateIfNotExist())
            {

                blobContainer.SetPermissions(
                   new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob }
                );
            }


        }
        public List<ViewModelFile> GetAllPreviouslyUploadedFiles()
        {
            List<ViewModelFile> list = new List<ViewModelFile>();

            var listBlobs = blobContainer.ListBlobs();
            foreach (var blob in listBlobs)
            {

                var segments =
                    blob.Uri.Segments;

                System.IO.FileInfo fi = new FileInfo(segments[3]);

                list.Add(new ViewModelFile()
                {
                    Name = fi.Name   ,
                    Extension = fi.Extension,
                    Path = blob.Uri.AbsolutePath
                });
            }

            return list;

        }


        public ViewModelFile GetFileByName(string name)
        {

            CloudBlob blob =
                blobContainer.GetBlobReference(name);

            if (blob != null)
            {
                return new ViewModelFile()
                {
                    Name = blob.Uri.ToString(),
                    Extension = blob.Uri.ToString(),
                    Path = blob.Uri.ToString()
                };
            }
            else
            {
                return null;
            }

        }

        public void Save(Stream stream, string fileName)
        {
           

            CloudBlob blob =
                blobContainer.GetBlobReference(fileName);

        
            blob.UploadFromStream(stream);


        }
    }
}